import React, { useRef, useState } from 'react';
import GoBack from "@/components/TheGoBack";
import { useLocation, useNavigate } from 'react-router-dom';
import {
  ProForm,
  ProFormCheckbox, ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormDateTimeRangePicker,
  ProFormSelect,
  ProFormText
} from '@ant-design/pro-components';
import { Col, message, Row, Space } from "antd";
import CouponList from "@/pages/couponManagement/timedTask/components/add/couponList.jsx";
import UserList from "@/pages/couponManagement/timedTask/components/add/userList.jsx";
import moment from "moment";
import { apiPostCouponTimerAdd, apiPostCouponTimerModify, apiPostTimerCouponPage, apiPostTimerUserPage } from "@/api/couponManagement/timeTask.jsx";


const Add = () => {
  const navigate = useNavigate()
  const location = useLocation();
  const formRef = useRef();
  const format = "YYYY-MM-DD HH:mm";
  const mode = location.state.mode;
  const couponTimerCenterId = location.state.id;
  const pushDateTime = location.state.time;

  let title = null
  switch (mode) {
    case 'add':
      title = "创建任务";
      break;
    case 'edit':
      title = "编辑任务";
      break;
    case 'view':
      title = "活动详情";
      break;
    default:
      break;
  }

  const formItemLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
  }
  const disabledDate = current => {
    return current && current < moment().startOf('days');
  }
  const disabledTime = (date) => {

    // console.log(date)
    let currentDay = moment().date();    //当下的时间
    let currentHours = moment().hours();
    let currentMinutes = moment().minutes();  //设置的时间
    let settingHours = moment(date).hours();
    let settingDay = moment(date).date();

    // console.log(currentDay, currentHours, currentMinutes, settingHours, settingDay)
    if (date && settingDay === currentDay && settingHours === currentHours) {
      return {
        disabledHours: () => range(0, currentHours - 1),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
        disabledMinutes: () => range(0, currentMinutes + 4),
      };
    } else if (date && settingDay === currentDay && settingHours > currentHours) {
      return {
        disabledHours: () => range(0, currentHours - 1),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间
      };
    } else if (date && settingDay === currentDay && settingHours < currentHours) {
      return {
        disabledHours: () => range(0, currentHours - 1),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
        disabledMinutes: () => range(0, currentMinutes + 4),
      }
    } else if (date && settingDay > currentDay) {
      return {
        disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
        disabledMinutes: () => [],
      }
    }
  }
  const range = (start, end) => {
    const result = [];
    for (let i = start; i <= end; i++) {
      result.push(i);
    }
    return result;
  }
  return (
    <div className={'wrap-box'}>
      <GoBack title={title} />
      <div className={'wrap-box-content'}>
        <ProForm
          {...formItemLayout}
          readonly={mode === 'view'}
          formRef={formRef}
          layout={'horizontal'}
          submitter={{
            render: (props, doms) => {
              if (mode === 'view') {
                return null
              }
              return <Row>
                <Col span={22} offset={2}>
                  <Space>{doms}</Space>
                </Col>
              </Row>
            },
          }}
          onValuesChange={() => { }}
          onFinish={async (values) => {
            if (mode === "add") {
              await apiPostCouponTimerAdd(values).then(res => {
                if (res.code === 0) {
                  message.success('提交成功');
                  navigate(-1)
                }
              })
            } else {
              await apiPostCouponTimerModify({ couponTimerCenterId, ...values }).then(res => {
                if (res.code === 0) {
                  message.success('提交成功');
                  navigate(-1)
                }
              })
            }
          }}
          onFinishFailed={(values) => {
            if (values.errorFields.length) {
              message.error('请完善数据')
            }
          }}
          params={{}}
          initialValues={{
            couponList: [],
            userList: []
          }}
          request={async () => {
            if (mode !== "add") {
              let couponres = await apiPostTimerCouponPage({ pageNo: 1, pageSize: -1, couponTimerCenterId })
              let userres = await apiPostTimerUserPage({ pageNo: 1, pageSize: -1, couponTimerCenterId })
              return {
                pushDateTime,
                couponList: couponres.rows.map(item => item.couponInfo),
                userList: userres.rows.map(item => item.memberInfo)
              }
            } else {
              return {}
            }
          }}
        >
          <ProFormDatePicker
            name="pushDateTime"
            label="发送时间"
            width="md"
            fieldProps={{
              format: (value) => value.format('YYYY-MM-DD HH:mm:ss'),
              showNow: false,
              showTime: {
                format: 'HH:mm',
                defaultValue: moment(new Date().setMinutes(new Date().getMinutes() + 5))
              },
              disabledDate: disabledDate,
              disabledTime: disabledTime
            }}
            rules={[
              {
                required: true,
              }
            ]}
          />
          <ProForm.Item
            label="优惠券"
            name="couponList"
            trigger="onValuesChange"
            rules={
              [
                {
                  required: true,
                  validator(_, value) {
                    if (value.length) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('请选择至少一张有效的优惠券'));
                  },
                },
              ]
            }
          >
            <CouponList mode={mode} />
          </ProForm.Item>
          <ProForm.Item
            label="发送人群"
            name="userList"
            trigger="onValuesChange"
            rules={
              [
                {
                  required: true,
                  validator(_, value) {
                    if (value.length) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('请选择至少一个用户'));
                  },
                },
              ]
            }
          >
            <UserList mode={mode} />
          </ProForm.Item>
        </ProForm>
      </div>
    </div>
  )
};
export default Add;
